package database

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"management/util"
)

var DB *gorm.DB

func connectionDatabase(info util.Database) (*gorm.DB, error) {
	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local", info.Username, info.Password, info.Host, info.Port, info.DBName)
	DB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return nil, err
	}
	return DB, nil
}

func GetDBInstance() (*gorm.DB, error) {
	if DB != nil {
		return DB, nil
	}
	config, err := util.GetConfig()
	if err != nil {
		return nil, err
	}
	db, err := connectionDatabase(config.Database)
	DB = db
	if err != nil {
		return nil, err
	}
	return DB, err
}
